package com.ithinks.flow.common.utils.protocol.udp.broadcast.bcside;

import com.ithinks.flow.common.utils.protocol.udp.broadcast.LogConst;
import com.ithinks.flow.common.utils.protocol.udp.broadcast.LogMsg;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;

/**
 * @Description
 * @ClassName LogEventBroadcaster
 * @Author MR.LI
 * @date 2020.12.13 17:57
 */
public class LogEventBroadcaster {

    private final EventLoopGroup group;

    private final Bootstrap bootstrap;

    public LogEventBroadcaster(InetSocketAddress remoteAddress) {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new LogEventEncoder(remoteAddress));
    }

    public void run() throws InterruptedException {
        Channel ch = bootstrap.bind(0).sync().channel();
        long count = 0;
        for(;;){
            ch.writeAndFlush(new LogMsg(null,++count, LogConst.getLogInfo()));
            try {
                //休眠 2 秒，如果被中断，则退出循环；
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.interrupted();
                break;
            }
        }
    }

    public static void main(String[] args) {
        LogEventBroadcaster logEventBroadcaster = new LogEventBroadcaster(
                new InetSocketAddress("255.255.255.255",LogConst.MONITOR_SIDE_PORT)
        );
        try {
            logEventBroadcaster.run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            logEventBroadcaster.stop();
        }
    }
    public void stop() {
        group.shutdownGracefully();
    }
}
